/* Copyright (c) 2011-2013 ISP RAS, Moscow. For more information please write to

      mermakov@ispras.ru
      svartanov@ispras.ru

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package ru.ispras.coffeemachine.instrument;

import java.util.List;

import org.apache.bcel.Constants;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.ConstantClass;
import org.apache.bcel.classfile.ConstantInterfaceMethodref;
import org.apache.bcel.classfile.ConstantMethodref;
import org.apache.bcel.classfile.ConstantNameAndType;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.generic.BIPUSH;
import org.apache.bcel.generic.BranchInstruction;
import org.apache.bcel.generic.ClassGen;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.FieldInstruction;
import org.apache.bcel.generic.IINC;
import org.apache.bcel.generic.INSTANCEOF;
import org.apache.bcel.generic.INVOKESTATIC;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.LDC;
import org.apache.bcel.generic.LDC2_W;
import org.apache.bcel.generic.LocalVariableInstruction;
import org.apache.bcel.generic.MULTIANEWARRAY;
import org.apache.bcel.generic.NEW;
import org.apache.bcel.generic.NEWARRAY;
import org.apache.bcel.generic.PUSH;
import org.apache.bcel.generic.RET;
import org.apache.bcel.generic.SIPUSH;

import ru.ispras.coffeemachine.instrument.util.Utility;
import ru.ispras.coffeemachine.target.Bytecode;
import ru.ispras.coffeemachine.target.Type;
import ru.ispras.coffeemachine.util.Logger;
import ru.ispras.coffeemachine.util.Options;

/**
 * One current instruction instrumentation using <tt>Daemon</tt> methods
 *
 * @author Sergey Vartanov (me@enzet.ru)
 * @author Mikhail Ermakov (mermakov@ispras.ru)
 * @version 1.2.0
 * @since 2011-09-12
 */
public class Milk
{
	/**
	 * Interface for extra instruction generation on method enter/exit
	 */
	protected interface CustomListGenerator {

		/**
		 * Checks whether current method requires extra instruction generation
		 *
		 * @param milk calling {@link Milk} instance
		 * @return <code>true</code> if extra instrumentation is requires, <code>false</code> otherwise
		 */
		public boolean checkApplicability(Milk milk);

		/**
		 * Returns an {@link InstructionList} to be inserted before the first method instruction
		 *
		 * @param milk calling {@link Milk} instance
		 * @return an {@link InstructionList} to be inserted before the first method instruction
		 */
		public InstructionList generateEnterList(Milk milk);

		/**
		 * Returns an {@link InstructionList} to be inserted before exit instruction of method (return, athrow)
		 *
		 * @param milk calling {@link Milk} instance
		 * @return an {@link InstructionList} to be inserted before the first method instruction
		 */
		public InstructionList generateExitList(Milk milk);

	}

	protected InstructionList instructionList = new InstructionList();
	protected CoffeeInstructionFactory factory;
	protected ConstantPoolGen cpg;

	protected CoffeeMethodGen currentMethod;
	protected ClassGen targetClass;

	protected String className;

	protected static final String targetPackage = "ru/ispras/coffeemachine/target/";
	protected static final String typeClass = "Lru/ispras/coffeemachine/target/Type;";
	protected static final String bytecodeClass = "Lru/ispras/coffeemachine/target/Bytecode;";

	protected String updateStack = null;

	protected boolean removeInstruction = false;

	static int pc;

	protected Integer activeInvoke = null;
	public boolean isLastInstruction;

	public Milk(ClassGen targetClass, ConstantPoolGen cpg)
	{
		factory = CoffeeInstructionFactory.createFactory(targetClass, cpg);
		this.cpg = cpg;
		this.targetClass = targetClass;
		Invoker.setClassContext(cpg, factory);
	}

	public static Milk createMilk(ClassGen targetClass, ConstantPoolGen cpg)
	{
		if (Options.concurrencyEnabled && Options.stpEnabled) {
			return new CombinedMilk(targetClass, cpg);
		} else if (Options.concurrencyEnabled) {
			return new ConcurrencyMilk(targetClass, cpg);
		} else if (Options.stpEnabled) {
			return new DaemonMilk(targetClass, cpg);
		} else {
			return new Milk(targetClass, cpg);
		}
	}

	/**
	 * Returns an {@link Mokka.TargetedInstructionList} to be added into bytecode before instruction
	 *
	 * @param ih instruction handler
	 * @return an {@link Mokka.TargetedInstructionList} to be added into bytecode before instruction
	 */
	public Mokka.TargetedInstructionList createBeforeList(InstructionHandle ih)
	{

		instructionList = new InstructionList();

		int opcode = ih.getInstruction().getOpcode();

		Object[] arguments = getArguments(ih);

		InstructionList prefixList = createPreList();
		if (prefixList != null)
		{
			instructionList.append(prefixList);
		}

		InstructionHandle jumpTarget = instructionList.getEnd();

		isLastInstruction = (ih.getNext() == null);
		removeInstruction = false;

		// @formatter:off
		try
		{
			switch (opcode)
			{
				case 0x00: break; // no operation

				case 0x01: pushnull(); break;

				case 0x02:
				case 0x03:
				case 0x04:
				case 0x05:
				case 0x06:
				case 0x07:
				case 0x08: pushconst(Type.I); break;
				case 0x09:
				case 0x0a: pushconst(Type.J); break;
				case 0x0b:
				case 0x0c:
				case 0x0d: pushconst(Type.F); break;
				case 0x0e:
				case 0x0f: pushconst(Type.D); break;

				case 0x10:
				case 0x11: pushconst(Type.I); break;
				case 0x12:
				case 0x13:
				case 0x14: pushconst(Type.valueOf((String) arguments[0])); break;

				case 0x15: xload((Integer) arguments[0], Type.I); break;
				case 0x16: xload((Integer) arguments[0], Type.J); break;
				case 0x17: xload((Integer) arguments[0], Type.F); break;
				case 0x18: xload((Integer) arguments[0], Type.D); break;
				case 0x19: xload((Integer) arguments[0], Type.R); break;
				case 0x1a:
				case 0x1b:
				case 0x1c:
				case 0x1d: xload(opcode - 0x1a, Type.I); break;
				case 0x1e:
				case 0x1f:
				case 0x20:
				case 0x21: xload(opcode - 0x1e, Type.J); break;
				case 0x22:
				case 0x23:
				case 0x24:
				case 0x25: xload(opcode - 0x22, Type.F); break;
				case 0x26:
				case 0x27:
				case 0x28:
				case 0x29: xload(opcode - 0x26, Type.D); break;
				case 0x2a:
				case 0x2b:
				case 0x2c:
				case 0x2d: xload(opcode - 0x2a, Type.R); break;

				case 0x2e: xaload(Type.I); break;
				case 0x2f: xaload(Type.J); break;
				case 0x30: xaload(Type.F); break;
				case 0x31: xaload(Type.D); break;
				case 0x32: xaload(Type.R); break;
				case 0x33: xaload(Type.B); break;
				case 0x34: xaload(Type.C); break;
				case 0x35: xaload(Type.S); break;

				case 0x36: xstore((Integer) arguments[0], Type.I); break;
				case 0x37: xstore((Integer) arguments[0], Type.J); break;
				case 0x38: xstore((Integer) arguments[0], Type.F); break;
				case 0x39: xstore((Integer) arguments[0], Type.D); break;
				case 0x3a: xstore((Integer) arguments[0], Type.R); break;
				case 0x3b:
				case 0x3c:
				case 0x3d:
				case 0x3e: xstore(opcode - 0x3b, Type.I); break;
				case 0x3f:
				case 0x40:
				case 0x41:
				case 0x42: xstore(opcode - 0x3f, Type.J); break;
				case 0x43:
				case 0x44:
				case 0x45:
				case 0x46: xstore(opcode - 0x43, Type.F); break;
				case 0x47:
				case 0x48:
				case 0x49:
				case 0x4a: xstore(opcode - 0x47, Type.D); break;
				case 0x4b:
				case 0x4c:
				case 0x4d:
				case 0x4e: xstore(opcode - 0x4b, Type.R); break;

				case 0x4f: xastore(Type.I); break;
				case 0x50: xastore(Type.J); break;
				case 0x51: xastore(Type.F); break;
				case 0x52: xastore(Type.D); break;
				case 0x53: xastore(Type.R); break;
				case 0x54: xastore(Type.B); break;
				case 0x55: xastore(Type.C); break;
				case 0x56: xastore(Type.S); break;

				case 0x57: pop(); break;

				case 0x58: pop2(); break;

				case 0x59: dup(1, 0); break;
				case 0x5a: dup(1, 1); break;
				case 0x5b: dup(1, 2); break;
				case 0x5c: dup(2, 0); break;
				case 0x5d: dup(2, 1); break;
				case 0x5e: dup(2, 2); break;

				case 0x5f: swap(); break;

				case 0x60: arithmetic(Bytecode.PLUS, Type.I, Type.I); break;
				case 0x61: arithmetic(Bytecode.PLUS, Type.J, Type.J); break;
				case 0x62: arithmetic(Bytecode.PLUS, Type.F, Type.F); break;
				case 0x63: arithmetic(Bytecode.PLUS, Type.D, Type.D); break;
				case 0x64: arithmetic(Bytecode.MINUS, Type.I, Type.I); break;
				case 0x65: arithmetic(Bytecode.MINUS, Type.J, Type.J); break;
				case 0x66: arithmetic(Bytecode.MINUS, Type.F, Type.F); break;
				case 0x67: arithmetic(Bytecode.MINUS, Type.D, Type.D); break;
				case 0x68: arithmetic(Bytecode.MULT, Type.I, Type.I); break;
				case 0x69: arithmetic(Bytecode.MULT, Type.J, Type.J); break;
				case 0x6a: arithmetic(Bytecode.MULT, Type.F, Type.F); break;
				case 0x6b: arithmetic(Bytecode.MULT, Type.D, Type.D); break;
				case 0x6c: arithmetic(Bytecode.DIV, Type.I, Type.I); break;
				case 0x6d: arithmetic(Bytecode.DIV, Type.J, Type.J); break;
				case 0x6e: arithmetic(Bytecode.DIV, Type.F, Type.F); break;
				case 0x6f: arithmetic(Bytecode.DIV, Type.D, Type.D); break;
				case 0x70: arithmetic(Bytecode.MOD, Type.I, Type.I); break;
				case 0x71: arithmetic(Bytecode.MOD, Type.J, Type.J); break;
				case 0x72: arithmetic(Bytecode.MOD, Type.F, Type.F); break;
				case 0x73: arithmetic(Bytecode.MOD, Type.D, Type.D); break;
				case 0x74: arithmetic(Bytecode.UMINUS, Type.I); break;
				case 0x75: arithmetic(Bytecode.UMINUS, Type.J); break;
				case 0x76: arithmetic(Bytecode.UMINUS, Type.F); break;
				case 0x77: arithmetic(Bytecode.UMINUS, Type.D); break;
				case 0x78: arithmetic(Bytecode.SHL, Type.I, Type.I); break;
				case 0x79: arithmetic(Bytecode.SHL, Type.J, Type.I); break;
				case 0x7a: arithmetic(Bytecode.SHR, Type.I, Type.I); break;
				case 0x7b: arithmetic(Bytecode.SHR, Type.J, Type.I); break;
				case 0x7c: arithmetic(Bytecode.USHR, Type.I, Type.I); break;
				case 0x7d: arithmetic(Bytecode.USHR, Type.J, Type.I); break;
				case 0x7e: arithmetic(Bytecode.AND, Type.I, Type.I); break;
				case 0x7f: arithmetic(Bytecode.AND, Type.J, Type.J); break;
				case 0x80: arithmetic(Bytecode.OR, Type.I, Type.I); break;
				case 0x81: arithmetic(Bytecode.OR, Type.J, Type.J); break;
				case 0x82: arithmetic(Bytecode.XOR, Type.I, Type.I); break;
				case 0x83: arithmetic(Bytecode.XOR, Type.J, Type.J); break;

				case 0x84: iinc((Integer) arguments[0], (Integer) arguments[1]); break;

				case 0x85: convert(Type.I, Type.J); break;
				case 0x86: convert(Type.I, Type.F); break;
				case 0x87: convert(Type.I, Type.D); break;
				case 0x88: convert(Type.J, Type.I); break;
				case 0x89: convert(Type.J, Type.F); break;
				case 0x8a: convert(Type.J, Type.D); break;
				case 0x8b: convert(Type.F, Type.I); break;
				case 0x8c: convert(Type.F, Type.J); break;
				case 0x8d: convert(Type.F, Type.D); break;
				case 0x8e: convert(Type.D, Type.I); break;
				case 0x8f: convert(Type.D, Type.J); break;
				case 0x90: convert(Type.D, Type.F); break;
				case 0x91: convert(Type.I, Type.B); break;
				case 0x92: convert(Type.I, Type.C); break;
				case 0x93: convert(Type.I, Type.S); break;

				case 0x94: cmp(Type.J); break;
				case 0x95: cmp(Type.F); break;
				case 0x96: cmp(Type.F); break;
				case 0x97: cmp(Type.D); break;
				case 0x98: cmp(Type.D); break;

				case 0x99: zeroCompare(Bytecode.EQ); break;
				case 0x9a: zeroCompare(Bytecode.NE); break;
				case 0x9b: zeroCompare(Bytecode.LT); break;
				case 0x9c: zeroCompare(Bytecode.GE); break;
				case 0x9d: zeroCompare(Bytecode.GT); break;
				case 0x9e: zeroCompare(Bytecode.LE); break;

				case 0x9f: compare(Bytecode.EQ); break;
				case 0xa0: compare(Bytecode.NE); break;
				case 0xa1: compare(Bytecode.LT); break;
				case 0xa2: compare(Bytecode.GE); break;
				case 0xa3: compare(Bytecode.GT); break;
				case 0xa4: compare(Bytecode.LE); break;
				case 0xa5: compareRefs(); break;
				case 0xa6: compareRefs(); break;

				case 0xa7: break; // goto

				case 0xaa: pop(); break;
				case 0xab: pop(); break;

				case 0xac:
				case 0xad:
				case 0xae:
				case 0xaf:
				case 0xb0: xreturn(true); break;
				case 0xb1: xreturn(false); break;

				case 0xb2: getstatic(arguments); break;
				case 0xb3: putstatic(arguments); break;
				case 0xb4: getfield(arguments); break;
				case 0xb5: putfield(arguments); break;

				case 0xb6: invoke(arguments, Constants.INVOKEVIRTUAL); break;
				case 0xb7: invoke(arguments, Constants.INVOKESPECIAL); break;
				case 0xb8: invoke(arguments, Constants.INVOKESTATIC); break;
				case 0xb9: invoke(arguments, Constants.INVOKEINTERFACE); break;

				case 0xba: break; // dynamic invocation

				case 0xbb: xnew((String) arguments[0]); break;

				case 0xbc:
				case 0xbd: newarray((String) arguments[0]); break;

				case 0xbe: arraylength(); break;

				case 0xbf: athrow(); break;

				case 0xc0: break; // checkcast

				case 0xc1: xinstanceof((String) arguments[0]); break;

				case 0xc2: monitor(true); break;
				case 0xc3: monitor(false); break;

				case 0xc4: break; // wide

				case 0xc5: multianewarray((Integer) arguments[0]); break;

				case 0xc6: nullCompare(false); break;
				case 0xc7: nullCompare(true); break;

				case 0xc8: break; // goto wide

				case 0xc9: break; // jump to subroutine wide

				case 0xca: break; // breakpoint

				case 0xfe: break; // impdep1
				case 0xff: break; // impdep2
			}
		}
		catch (ClassCastException e)
		{
			Logger.error("cannot cast argument");
			e.printStackTrace();
		}
		// @formatter:on

		if (Options.printInstructions)
		{
			String instructionText = "# " + factory.getClassGen().getClassName() + "."
				+ currentMethod.getName() + " " + ih.getPosition() + " "
				+ Constants.OPCODE_NAMES[opcode] + " (" + Integer.toHexString(opcode) + ")";

			for (Object o : arguments)
			{
				if (o != null)
				{
					instructionText += " " + o;
				}
			}
			instructionList.insert(factory.createPrintln(instructionText.toString())); // TODO: is correct?
			instructionList.append(new PUSH(cpg, "CONC:" + instructionText.toString()));
			appendMethod("Daemon", "println", "(Ljava/lang/String;)V");
		}
		if (jumpTarget != null) {
			jumpTarget = jumpTarget.getNext();
		} else {
			jumpTarget = instructionList.getStart();
		}

		if (ih.getPosition() == 0) {
			InstructionList extra = createFirstList();
			if (extra != null)
			{
				instructionList.insert(extra);
			}
		}
		return new Mokka.TargetedInstructionList(instructionList, jumpTarget, removeInstruction);
	}

	protected InstructionList createPreList() { return null; }

	protected InstructionList createExceptionHandlerList() { return null; }

	protected InstructionList createFirstList() { return null; }

	/**
	 * Returns an {@link Mokka.TargetedInstructionList} to be added into bytecode after instruction
	 *
	 * @param ih instruction handler
	 * @return an {@link Mokka.TargetedInstructionList} to be added into bytecode after instruction
	 */
	public Mokka.TargetedInstructionList createAfterList(InstructionHandle ih)
	{
		instructionList = new InstructionList();

		Object[] arguments = getArguments(ih);

		int opcode = ih.getInstruction().getOpcode();

		switch (opcode)
		{
			case 0xb6: invokeAfter(arguments, Constants.INVOKEVIRTUAL); break;
			case 0xb7: invokeAfter(arguments, Constants.INVOKESPECIAL); break;
			case 0xb8: invokeAfter(arguments, Constants.INVOKESTATIC); break;
			case 0xb9: invokeAfter(arguments, Constants.INVOKEINTERFACE); break;

			case 0xc2: monitorAfter(true); break;
			case 0xc3: monitorAfter(false); break;

			case 0xbb: xnewAfter(); break;
			default: return null;
		}
		InstructionHandle jumpTarget = instructionList.getStart();

		return new Mokka.TargetedInstructionList(instructionList, jumpTarget);
	}

	/**
	 * Appends a method invocation instruction with specified class name, method name and method signature) to current version of <code>instructionList</code>
	 *
	 * @param className fully specified class name (e.g. java.lang.String)
	 * @param name method name
	 * @param signature fully specified method name (e.g. charAt(I)C)
	 * @return {@link InstructionHandle} for appended instruction
	 */
	InstructionHandle appendMethod(String className, String name, String signature)
	{
		return appendMethod(className, name, signature, instructionList);
	}

	/**
	 * Appends a method invocation instruction with specified class name, method name and method signature) to specified instruction list
	 *
	 * @param className fully specified class name (e.g. java.lang.String)
	 * @param name method name
	 * @param signature fully specified method name (e.g. charAt(I)C)
	 * @param il target instruction list
	 * @return {@link InstructionHandle} for appended instruction
	 */
	InstructionHandle appendMethod(String className, String name, String signature, InstructionList il)
	{
		int method = cpg.addMethodref(targetPackage + className, name, signature);
		return il.append(new INVOKESTATIC(method));
	}

	/**
	 * Same as standard createMethod, only uses Milk#className as invoked method class
	 */
	InstructionHandle appendMethod(String name, String signature)
	{
		return appendMethod(name, signature, instructionList);
	}

	/**
	 * Same as standard createMethod, only uses Milk#className as invoked method class
	 */
	InstructionHandle appendMethod(String name, String signature, InstructionList il)
	{
		return appendMethod(className, name, signature, il);
	}

	/**
	 * Prepends a method invocation instruction with specified class name, method name and method signature) to current version of <code>instructionList</code>
	 *
	 * @param className fully specified class name (e.g. java.lang.String)
	 * @param name method name
	 * @param signature fully specified method name (e.g. charAt(I)C)
	 * @return {@link InstructionHandle} for appended instruction
	 */
	InstructionHandle prependMethod(String className, String name, String signature)
	{
		return prependMethod(className, name, signature, instructionList);
	}

	/**
	 * Appends a method invocation instruction with specified class name, method name and method signature) to specified instruction list
	 *
	 * @param className fully specified class name (e.g. java.lang.String)
	 * @param name method name
	 * @param signature fully specified method name (e.g. charAt(I)C)
	 * @param il target instruction list
	 * @return {@link InstructionHandle} for appended instruction
	 */
	InstructionHandle prependMethod(String className, String name, String signature, InstructionList il)
	{
		int method = cpg.addMethodref(targetPackage + className, name, signature);
		return il.insert(new INVOKESTATIC(method));
	}

	/*
	 * Same as standard createMethod, only uses Milk#className as invoked method class
	 */
	InstructionHandle prependMethod(String name, String signature)
	{
		return prependMethod(name, signature, instructionList);
	}

	/*
	 * Same as standard createMethod, only uses Milk#className as invoked method class
	 */
	InstructionHandle prependMethod(String name, String signature, InstructionList il)
	{
		return prependMethod(className, name, signature, il);
	}

	/*
	 * Instruction instrumentation handlers
	 */

	protected void pushnull() {}

	protected void pushconst(Type t) {}

	protected void xload(int index, Type type) {}

	protected void xaload(Type type) {}

	protected void xstore(int index, Type t) {}

	protected void xastore(Type type) {}

	protected void pop() {}

	protected void pop2() {}

	protected void dup(int num, int before) {}

	protected void swap() {}

	protected void arithmetic(Bytecode kind, Type... types) {}

	protected void iinc(int index, int constant) {}

	protected void convert(Type from, Type to) {}

	protected void cmp(Type type) {}

	protected void zeroCompare(Bytecode type) {}

	protected void compare(Bytecode type) {}

	protected void compareRefs() {}

	protected void xreturn(boolean popStack) {}

	protected void getstatic(Object[] arguments) {}

	protected void putstatic(Object[] arguments) {}

	protected void getfield(Object[] arguments) {}

	protected void putfield(Object[] arguments) {}

	protected void invoke(Object[] arguments, short type) {}

	protected void xnew(String className) {}

	protected void newarray(String type) {}

	protected void athrow() {}

	protected void arraylength() {}

	protected void xinstanceof(String className) {}

	protected void monitor(boolean isEnter) {}

	protected void multianewarray(int dimensions) {}

	protected void nullCompare(boolean isInverted) {}

	/*
	 * Instructions after
	 */

	protected void invokeAfter(Object []parameters, short type) {}

	protected void xnewAfter() {}

	protected void monitorAfter(boolean isEnter) {}

	/*
	 * Utility methods
	 */

	public static boolean isReturnInstruction(int opcode)
	{
		return ((0xac <= opcode) && (opcode <= 0xb1));
	}

	/**
	 * Parses method signature obtaining parameter types and
	 * returns an array of item size for each type (see {@link Type#getItemSize()}).
	 *
	 * Method takes into account whether target method is static or not.
	 * Non-static methods are treated as if they have an
	 * extra object reference parameter as first parameter.
	 *
	 * @param signature fully specified methods signature
	 * @param isStatic <code>true</code> if target method is static, <code>false</code> otherwise.
	 * @return item size array for parameters
	 */
	protected int [] getSizeSignature (String signature, boolean isStatic) {

		int start = signature.indexOf('(');
		int end = signature.indexOf(')');
		List<Type> types = Type.parseSignature(signature.substring(start + 1, end));
		int []result;
		if (isStatic) {
			result = new int[types.size()];
			start = 0;
		} else {
			result = new int[types.size() + 1];
			result[0] = 1;
			start = 1;
		}

		for (int i = 0; i < types.size(); i ++) {
			result[i + start] = types.get(i).getItemSize();
		}

		return result;
	}

	/**
	 * Checks target class and its parent classes and
	 * finds the deepest in hierarchy class with specified method implementation.
	 *
	 * @param className target class name
	 * @param methodName target method name
	 * @param signature target method signature
	 * @return name of the deepest in hierarchy class with specified method implementation
	 */
	protected String getRealClassName(String className, String methodName, String signature)
	{
		try
		{
			JavaClass invokedClass = Repository.lookupClass(className);

			if (!Utility.containsMethod(invokedClass, methodName, signature))
			{
				JavaClass[] superClasses = invokedClass.getSuperClasses();

				for (JavaClass superClass : superClasses)
				{
					if (Utility.containsMethod(superClass, methodName, signature))
					{
						return superClass.getClassName().replaceAll("\\.", "/");
					}
				}
			}
		}
		catch (ClassNotFoundException e)
		{}
		return className;
	}

	void setCurrentMethod(CoffeeMethodGen currentMethod)
	{
		this.currentMethod = currentMethod;

		Invoker.setMethod(currentMethod);
	}

	// Utility methods

	protected boolean isInit()
	{
		return currentMethod.getName().equals("<init>");
	}

	protected boolean isInitOrClinit()
	{
		return currentMethod.getName().equals("<init>") || currentMethod.getName().equals("<clinit>");
	}

	protected int getSignatureHash() {
		return (currentMethod.getName() + currentMethod.getSignature()).hashCode();
	}


	/**
	 * Inserts a stack push instruction with current <i>position of code</i> as argument into target instruction list.
	 * @param target target instruction list
	 */
	protected void updateCodePosition(InstructionList target) {
		target.append(new PUSH(cpg, pc));
	}

	/**
	 * Inserts a stack push instruction with current <i>position of code</i> as argument into current instruction list.
	 */
	protected void updateCodePosition() {
		updateCodePosition(instructionList);
	}

	/**
	 * Returns Daemon formatted string representation of push instructions values.
	 * @param object push instruction value
	 * @return Daemon formatted string representation of constant value
	 */
	protected String transformLDCValue(Object object) {
		if (object instanceof String) {
			return ru.ispras.coffeemachine.target.Type.T.toString();
		}
		if ((object.getClass() == int.class) || (object instanceof Integer)) {
			return ru.ispras.coffeemachine.target.Type.I.toString();
		}
		if ((object.getClass() == long.class) || (object instanceof Long)) {
			return ru.ispras.coffeemachine.target.Type.J.toString();
		}
		if ((object.getClass() == float.class) || (object instanceof Float)) {
			return ru.ispras.coffeemachine.target.Type.F.toString();
		}
		if ((object.getClass() == double.class) || (object instanceof Double)) {
			return ru.ispras.coffeemachine.target.Type.D.toString();
		}
		return ru.ispras.coffeemachine.target.Type.R.toString();
	}

	/**
	 * Returns bytecode instruction arguments
	 * @param opcode target instruction opcode
	 */
	protected Object[] getArguments(InstructionHandle ih)
	{
		Object[] arguments = {null, null, null, null};

		int opcode = ih.getInstruction().getOpcode();

		// @formatter:off

		switch (opcode)
		{
			case 0x10:
				arguments[0] = ((BIPUSH) ih.getInstruction()).getValue();
				break;

			case 0x11:
				arguments[0] = ((SIPUSH) ih.getInstruction()).getValue();
				break;

			case 0x12: case 0x13:
				arguments[0] = transformLDCValue(((LDC) ih.getInstruction()).getValue(cpg));
				break;

			case 0x14:
				arguments[0] = transformLDCValue(((LDC2_W) ih.getInstruction()).getValue(cpg));
				break;

			case 0x15: case 0x16: case 0x17: case 0x18: case 0x19:
			case 0x36: case 0x37: case 0x38: case 0x39: case 0x3a:
				arguments[0] = ((LocalVariableInstruction) ih.getInstruction()).getIndex();
				break;

			case 0x84:
				arguments[0] = ((LocalVariableInstruction) ih.getInstruction()).getIndex();
				arguments[1] = ((IINC) ih.getInstruction()).getIncrement();
				break;

			case 0x99: case 0x9a: case 0x9b: case 0x9c: case 0x9d: case 0x9e:
			case 0x9f: case 0xa0: case 0xa1: case 0xa2: case 0xa3: case 0xa4:
			case 0xa5: case 0xa6: case 0xa7: case 0xa8:
			case 0xc6: case 0xc7:
				arguments[0] = ((BranchInstruction) ih.getInstruction()).getTarget().getPosition();
				break;

			case 0xa9:
				arguments[0] = ((RET) ih.getInstruction()).getIndex();
				break;

			// Get and put static and field

			case 0xb2: case 0xb3: case 0xb4: case 0xb5:
				FieldInstruction fieldInst = (FieldInstruction) ih.getInstruction();
				arguments[0] = fieldInst.getReferenceType(cpg).toString() + "." + fieldInst.getFieldName(cpg);
				arguments[1] = fieldInst.getFieldType(cpg).getSignature();
				break;

			case 0xb6: // invoke virtual
			case 0xb7: // invoke special
			case 0xb8: // invoke static
				ConstantMethodref c = (ConstantMethodref) cpg.getConstant(((InvokeInstruction) ih.getInstruction()).getIndex());
				ConstantClass c1 = (ConstantClass) cpg.getConstant(c.getClassIndex());
				ConstantNameAndType c2 = (ConstantNameAndType) cpg.getConstant(c.getNameAndTypeIndex());

				arguments[0] = ((ConstantUtf8) cpg.getConstant(c1.getNameIndex())).getBytes();
				arguments[1] = ((ConstantUtf8) cpg.getConstant(c2.getNameIndex())).getBytes();
				arguments[2] = ((ConstantUtf8) cpg.getConstant(c2.getSignatureIndex())).getBytes();

				break;

			case 0xb9: // invoke interface
				ConstantInterfaceMethodref ci = (ConstantInterfaceMethodref) cpg.getConstant(((InvokeInstruction) ih.getInstruction()).getIndex());
				ConstantClass ci1 = (ConstantClass) cpg.getConstant(ci.getClassIndex());
				ConstantNameAndType ci2 = (ConstantNameAndType) cpg.getConstant(ci.getNameAndTypeIndex());

				arguments[0] = ((ConstantUtf8) cpg.getConstant(ci1.getNameIndex())).getBytes();
				arguments[1] = ((ConstantUtf8) cpg.getConstant(ci2.getNameIndex())).getBytes();
				arguments[2] = ((ConstantUtf8) cpg.getConstant(ci2.getSignatureIndex())).getBytes();
				break;

				// I don't print count

			case 0xbb:
				arguments[0] = ((NEW)ih.getInstruction()).getType(cpg).getSignature();
				break;

			case 0xbc:
				arguments[0] = ((NEWARRAY) ih.getInstruction()).getType().getSignature().substring(1);
				break;

			case 0xc1:
				arguments[0] = ((INSTANCEOF) ih.getInstruction()).getType(cpg).getSignature();
				break;

			case 0xc5:
				arguments[0] = Integer.valueOf(((MULTIANEWARRAY)ih.getInstruction()).getDimensions());
				break;
		}
		// @formatter:on

		return arguments;
	}

}
